package com.tingyuge.base.thread.wang.complatefuture;

import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * Created by xiaodao
 * date: 2019/12/27
 * future 缺点1.自己判断完成了了没有
 * 1批future 需要主动的去拿,这样会阻塞主
 * 3.get() 之后的结果.没法在去调用一个future 必须重新定一个
 */
public class CompletableFutureExample1 {

    public static void main(String[] args) throws InterruptedException {
     /*   ExecutorService executorService = Executors.newFixedThreadPool(10);

        Future<?> future = executorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        while (!future.isDone()){

        }
        System.out.println("done");*/

      /*  CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
               int i= 2;

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).whenComplete((v,t)->{
            System.out.println(v+"--"+t);
        });
        System.out.println(" not block done");*/

        ExecutorService executorService = Executors.newFixedThreadPool(10);
//这样都是等着
//        List<Callable<Integer>> collect = IntStream.range(0, 10).boxed().map(i -> (Callable<Integer>) () -> get()).collect(Collectors.toList());

    /*    executorService.invokeAll(collect).stream().map(future->{
            try {
                return  future.get();
            }catch (Exception e) {
              throw new  RuntimeException(e);
            }
        }).parallel().forEach(CompletableFutureExample1::display);*/
         IntStream.range(0, 10).boxed().
                forEach(i->CompletableFuture.supplyAsync(CompletableFutureExample1::get)
                .thenAccept(CompletableFutureExample1::display)
                .whenComplete((v,t)->{
                    System.out.println(i + "done");
                }));

         Thread.currentThread().join();
    }
    private static void display(int data ){
        int i = ThreadLocalRandom.current().nextInt(20);
        System.out.println(Thread.currentThread().getName()+ "  display will be sleep "+ i+" 数据: "+ data);
        try {
            TimeUnit.SECONDS.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() +"  display execute done sleep "+ i+" 数据: "+ data);
    }
    private static int get(){
        int i = ThreadLocalRandom.current().nextInt(20);
        System.out.println(Thread.currentThread().getName()+ " get will be sleep "+" 数据: "+ i);
        try {
            TimeUnit.SECONDS.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return i;
    }
}
